package com.kgc.bage.springboot.controller;

import com.kgc.bage.springboot.constant.SystemConstant;
import com.kgc.bage.springboot.model.R;

import com.kgc.bage.springboot.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
import com.kgc.bage.springboot.model.TAdmin;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * 
 * @author bage
 *   TAdmin控制器
 * @date 2020-12-05 14:00:31
 */
@Controller
@RequestMapping("/tadmin")
public class TAdminController extends BaseController<TAdmin>{

	@RequestMapping(value = "/login")
	@ResponseBody
	public R login(@RequestBody TAdmin tAdmin){
		logger.info("用户名："+tAdmin.getUsername()+"-----"+"密码："+tAdmin.getPassword());
		try {
			TAdmin loginTAdmin = tAdminService.findObjectByPramas(tAdmin);
			if(loginTAdmin == null){
				return R.error("用户名或者密码错误");
			}else{
				/*return R.ok("登录成功");*/
				//把token返回给客户端-->客户端保存至cookie-->客户端每次请求附带cookie参数
				String JWT = JwtUtils.createJWT("1", loginTAdmin.getUsername(), SystemConstant.JWT_TTL);
				System.out.println(JWT);
				return R.ok(JWT);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("服务器异常");
		}

	}
	/**
	 * 刷新用户token
	 * @param request
	 * @return
	 */
	@GetMapping(value = "/refreshToken")
	public @ResponseBody R refreshToken(HttpServletRequest request){
		Claims claims = JwtUtils.validateJWT(request.getHeader("token")).getClaims();
		String JWT = JwtUtils.createJWT(claims.getId(),claims.getSubject(), SystemConstant.JWT_TTL);
		logger.info("新token"+JWT);
		return R.ok(JWT);
	}
}
